# -*- coding: utf-8 -*-
"""
Project: automation-api-project
Creator: jinsheng
Create time: 2021-11-09 09:19
IDE: PyCharm
Introduction: Hbase操作相关
"""

import happybase
from common.readConfig import WRConfigFile


class HbaseOperate:
    """
    python操作Hbase方法封装
    """

    def __init__(self, table_name='test', version=17):
        conf = WRConfigFile().read_conf
        # 下方的port是thrift服务的端口号，如被占用可以修改
        self.conn = happybase.Connection(host=conf('hbase', 'host_201'), port=conf('hbase', 'thrift_port_201'))
        if version == 221:
            self.conn = happybase.Connection(host=conf('hbase', 'host_221'), port=conf('hbase', 'thrift_port_221'))
        elif version == 156:
            self.conn = happybase.Connection(host=conf('hbase', 'host_156'), port=conf('hbase', 'thrift_port_156'))
        self.table = self.conn.table(table_name)

    def insert_data(self, row_key, data):
        """
        向HBASE数据库中插入数据
        @param row_key: rowkey
        @param data: 需要插入的数据，字典格式
        @return: None
        """
        try:
            self.table.put(row_key, data)
        except Exception as e:
            print(e)

    def delete_data(self, row_key):
        """
        根据rowkey删除数据
        @param row_key: rowkey
        @return: None
        """
        try:
            self.table.delete(row_key)
        except Exception as e:
            print(e)

    def query_data(self, row_start=None, row_stop=None, row_prefix=None):
        """
        读取HBASE数据
        @param row_start: 开始行
        @param row_stop: 结束行
        @param row_prefix: 根据前缀来匹配，例如 b'test'
        @return: 包含键值对的列表
        """
        res = []
        try:
            for k, v in self.table.scan(row_start=row_start, row_stop=row_stop, row_prefix=row_prefix):
                res.append((k, v))
        except Exception as e:
            print(e)
        return res

    def show_all_tables(self):
        """
        读取hbase所有表名
        @return: 表名组成的列表
        """
        try:
            return [res.decode() for res in self.conn.tables()]
        except Exception as e:
            print(e)

    def create_table(self, table_name):
        try:
            self.conn.create_table(table_name, {'cf': {}})
        except Exception as e:
            print(e)

    def delete_table(self, table_name):
        try:
            self.conn.delete_table(table_name, True)
        except Exception as e:
            print(e)

    def query_row(self, rowkey):
        """
        根据rowkey查询内容
        @param row_name: rowkey值
        @return:
        """
        return self.table.row(rowkey)


if __name__ == '__main__':
    ho = HbaseOperate()
    rank = 1
    for i in ho.show_all_tables():
        print(str(rank) + ': ' + i)
        rank += 1
